package com.novak.rss.reader;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;

public class MyFeedsViewActivity extends ListActivity
{
  private List<Feed> myFeeds = new ArrayList<Feed>();
  private RSSDBHelper dbHelper = null;

  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.frv);
    getListView().setOnCreateContextMenuListener(this);
    dbHelper = new RSSDBHelper(this);
    try
    {
      myFeeds = dbHelper.getAll();
    } catch (SQLException e)
    {
      showError("database error");
    }
    Feed ff = new Feed(getResources().getString(R.string.add),
        "nothing", Integer.MAX_VALUE);
    myFeeds.add(ff);
    resort(myFeeds);
    setListAdapter(new FeedsListAdapter(this, myFeeds));
  }

  public void toAdd()
  {
    // TODO coding
    Intent intent = new Intent();
    Bundle extras = new Bundle();
    ArrayList<String> values = new ArrayList<String>();
    for (int i = 0; i < myFeeds.size(); i++)
    {
      values.add(myFeeds.get(i).getUrl());
    }
    extras.putStringArrayList("urls", values);
    intent.putExtras(extras);
    intent.setClass(this, AddViewActivity.class);
    startActivityForResult(intent, 0);
  }

  protected void onListItemClick(ListView l, View v, int position,
      long id)
  {
    if (position == 0)
    {
      toAdd();

      return;
    }
    Feed f = (Feed) myFeeds.get(position);
    f.setCount(f.getCount() + 1);
    dbHelper.addCount(f);
    Bundle b = new Bundle();
    b.putString("path", f.getUrl());
    b.putString("title", f.getName());
    Intent intent = new Intent();
    intent.setClass(this, RSSProcessActivity.class);
    intent.putExtras(b);
    this.startActivityForResult(intent, 0);
  }

  private void resort(List<Feed> feeds)
  {
    Collections.sort(myFeeds, new FeedsComparator());
  }

  protected void onActivityResult(int requestCode, int resultCode,
      Intent data)
  {
    Bundle bunde;
    switch (resultCode)
    {
      case -1:
        bunde = data.getExtras();
        String error = bunde.getString("error");
        showError(error);
        break;
      case 1:
        bunde = data.getExtras();
        Feed f = new Feed(bunde.getString("name"), bunde
            .getString("url"), 1);
        try
        {
          dbHelper.add(f);
          myFeeds.add(f);
          setListAdapter(new FeedsListAdapter(this, myFeeds));
          Bundle b = new Bundle();
          b.putString("path", f.getUrl());
          b.putString("title", f.getName());
          Intent intent = new Intent();
          intent.setClass(this, RSSProcessActivity.class);
          intent.putExtras(b);
          this.startActivityForResult(intent, 0);
        } catch (SQLException e)
        {
          showError("database error");
        }
        break;
      default:
        break;
    }
  }

  private void showError(String mess)
  {
    new AlertDialog.Builder(this).setTitle("Message").setMessage(mess)
        .setNegativeButton(getResources().getString(R.string.ok),
            new DialogInterface.OnClickListener()
            {
              public void onClick(DialogInterface dialog, int which)
              {
              }
            }).show();
  }

  @Override
  public boolean onContextItemSelected(MenuItem item)
  {
    // TODO Auto-generated method stub
    switch (item.getItemId())
    {
      case 0:
        AdapterView.AdapterContextMenuInfo info;
        info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        dbHelper.delete(myFeeds.get(info.position));
        myFeeds.remove(info.position);
        setListAdapter(new FeedsListAdapter(this, myFeeds));
        return super.onContextItemSelected(item);
      case 1:
        return super.onContextItemSelected(item);
    }
    return super.onContextItemSelected(item);
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v,
      ContextMenuInfo menuInfo)
  {
    // TODO Auto-generated method stub
    AdapterView.AdapterContextMenuInfo info;
    info = (AdapterView.AdapterContextMenuInfo) menuInfo;
    if (info.position > 0)
    {
      Feed ff = myFeeds.get(info.position);
      menu.setHeaderTitle(ff.getName());
      menu.add(0, 0, 0, getResources().getString(R.string.delete));
      menu.add(0, 1, 0, getResources().getString(R.string.cancel));
    }
  }

  private class FeedsComparator implements Comparator<Feed>
  {

    @Override
    public int compare(Feed obj1, Feed obj2)
    {
      // TODO Auto-generated method stub
      if (obj1.getCount() > obj2.getCount())
      {
        return -1;
      } else if (obj1.getCount() == obj2.getCount())
      {
        return 0;
      } else
      {
        return 1;
      }
    }
  }

}
